package com.neuedu.elmserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.neuedu.elmserver.mapper.*;
import com.neuedu.elmserver.pojo.*;
import com.neuedu.elmserver.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.elmserver.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author wyh
 * @since 2024-11-07
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderitemMapper orderitemMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private FoodMapper foodMapper;


    /**
     * 生成订单
     *
     * @param userId
     * @param businessId
     * @param addressId
     * @param total
     * @return
     */
    @Transactional(rollbackFor = Exception.class) //事务管理
    @Override
    public ResultVO createOrders(Integer userId, Integer businessId, Integer addressId, Double total) {
        //1、生成订单记录：往订单表中插入一条数据
        Orders orders = new Orders();
        orders.setUserId(userId);
        orders.setBusinessId(businessId);
        orders.setAddressId(addressId);
        orders.setToatal(total);
        orders.setCreateTime(new Date());
        orders.setStatus(0); //0-未支付  1-已支付
        ordersMapper.insert(orders);
        //获取自增主键
        Integer orderKye = orders.getOrderId();//mybatisPlus会将自增的主键返回赋值给参数实体

        //2、生成订单详情记录：往订单详情表中插入数据
        //2-1:查询当前用户在当前商家的购物车记录
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id", userId);
        qw.eq("business_id", businessId);
        System.out.println(userId);
        System.out.println(businessId);
        List<Cart> cartList = cartMapper.selectList(qw);
        //2-2:生成订单详情记录
        System.out.println(cartList);
        for (Cart cart : cartList) {
            Orderitem orderitem = new Orderitem();
            orderitem.setFoodId(cart.getFoodId());
            orderitem.setQuantity(cart.getQuantity());
            orderitem.setOrderId(orderKye);
            orderitemMapper.insert(orderitem);
        }

        //3、删除当前用户在当前商家的购物车记录
        UpdateWrapper uw = new UpdateWrapper();
        uw.eq("user_id", userId);
        uw.eq("business_id", businessId);
        cartMapper.delete(uw);
        return ResultVO.ok("创建订单成功", orderKye);
    }

    /**
     * 根据订单编号查询订单信息
     *
     * @param id
     * @return
     */
    @Override
    public ResultVO getOrderById(Integer id) {
        //ordersMapper.selectById(id);//根据主键查询信息
        return ResultVO.ok("查询成功", ordersMapper.selectById(id));
    }

    /**
     * 根据订单编号查询商家信息
     * @param order_Id
     * @return
     */
    @Override
    public ResultVO getBusinessByOrderId(Integer order_Id) {
        //①先查询查询某个订单的商家ID
        QueryWrapper qw = new QueryWrapper();//查询的条件构造器
        qw.eq("order_id", order_Id);
//        List<Orders> listOrder=.selectList(qw);
        Orders orders = ordersMapper.selectById(order_Id);
        //②获取到每个订单的businessId,再根据businessId查询每个商家的名称和配送费
        Business business = businessMapper.selectById(orders.getBusinessId());

        return ResultVO.ok("查询成功", business);//根据主键查询信息
    }
    /**
     * 改变订单支付状态
     *
     * @param
     * @return
     */
    @Override
    public ResultVO changeStatus(Integer order_Id) {
        // 使用QueryWrapper进行条件查询
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", order_Id);

        // 根据条件查询订单对象
        Orders orders = ordersMapper.selectOne(queryWrapper);

        if (orders!= null && orders.getOrderId().equals(order_Id)) {
            // 设置要更新的字段值
            orders.setStatus(1);
            // 使用ordersMapper的update方法进行更新，传入更新的实体对象和更新条件
            ordersMapper.update(orders, queryWrapper);
        }
        return ResultVO.ok("订单状态更新成功");
    }
    @CrossOrigin
    /**
     * 查询某个用户的订单总价
     * @param userId
     * @return
     */
    @Override
    public ResultVO listOrder( Integer userId) {
        QueryWrapper qw=new QueryWrapper();//查询的条件构造器
        //select *from cart where  user_id=xx
        qw.eq("user_id",userId);
        return ResultVO.ok("查询成功",ordersMapper.selectList(qw));
    }

    /**
     * 根据用户ID查询订单中的商家信息
     * @param userId
     * @return
     */
    @Override
    public ResultVO listOrderByID( Integer userId) {
        QueryWrapper qw=new QueryWrapper();//查询的条件构造器
        //select *from cart where  user_id=xx
        qw.eq("user_id",userId);
        List<Orders> listOrder=ordersMapper.selectList(qw);
        //②获取到每个订单的businessId,再根据businessId查询每个商家的名称、地址和配送费
        for(Orders orders:listOrder){
            Business business=businessMapper.selectById(orders.getBusinessId());
            orders.setBusiness(business);
        }
        return ResultVO.ok("查询成功",listOrder);
    }
    /**
     * 根据用户ID查询订单中的food信息
     * @param userId
     * @return
     */
    public ResultVO getOrderItemsByUserId(Integer userId) {
        // ①先根据user_id在orders表中查询出订单号
        QueryWrapper<Orders> ordersQw = new QueryWrapper<>();
        ordersQw.eq("user_id", userId);
        List<Orders> ordersList = ordersMapper.selectList(ordersQw);

        // 用于存储最终查询到的所有订单明细信息
        List<Orderitem> allOrderItems = new ArrayList<>();

        // ②遍历每个订单，根据订单号在orderitem表中查出订单信息
        for (Orders order : ordersList) {
            Integer orderId = order.getOrderId();

            QueryWrapper<Orderitem> orderitemQw = new QueryWrapper<>();
            orderitemQw.eq("order_id", orderId);
            List<Orderitem> orderItems = orderitemMapper.selectList(orderitemQw);

            // ③针对每个订单明细，根据food_id去food表查看食物价格和名称
            for (Orderitem orderitem : orderItems) {
                Food food = foodMapper.selectById(orderitem.getFoodId());
                orderitem.setFood(food);
            }

            allOrderItems.addAll(orderItems);
        }

        return ResultVO.ok("查询成功", allOrderItems);
    }
}
